import { Crypto } from "rclink/lib";

const { CreateKeypair, CreateSelfSignedCertificate, GetKeyPEM, GetHashVal } =
  Crypto;

export const generateCert = (creditCode: string) => {
  const keypair = CreateKeypair("EC", "secp256k1");
  const prvKeyPEM = GetKeyPEM(keypair.prvKeyObj);
  const pubKeyPEM = GetKeyPEM(keypair.pubKeyObj);
  const serialNumber = GetHashVal({
    data: GetHashVal({ data: pubKeyPEM, provider: "jsrsasign" }),
    alg: "RIPEMD160",
    provider: "jsrsasign"
  }).toString("hex");
  const certValidStartUnixTime = parseInt(String(Date.now() / 1000), 10);
  const certValidEndUnixTime = certValidStartUnixTime + 99 * 365 * 24 * 3600;
  const certDN = `/CN=copRegUser${creditCode}`;
  const certPEM = CreateSelfSignedCertificate({
    serialNumber,
    sigAlg: "SHA256withECDSA",
    DN: certDN,
    notBefore: certValidStartUnixTime,
    notAfter: certValidEndUnixTime,
    keypair
  });
  return { prvKeyPEM, certPEM };
};
